package br.com.foxline.atlasmobile.dao;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import android.content.Context;

import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.dao.DaoManager;
import com.j256.ormlite.dao.ForeignCollection;
import com.j256.ormlite.support.ConnectionSource;

public abstract class GenericDao<T> {

	private Context context;
	private Dao<T, Long> dao;
	protected T entity;
	private Class<T> entityClass;

	public GenericDao(Context context) {
		this.context = context;
	}
	
	public GenericDao(Context context, T obj) {
		this.context = context;
		this.entity  = obj;
		this.entityClass = (Class<T>) obj.getClass();
		getDao();
	}

	public Dao<T, Long> getDao() {
		try {
			this.dao = DaoManager.createDao(getConnectionSource(), entity.getClass());
			return this.dao;
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}

	private ConnectionSource getConnectionSource() {
		return new DataBaseUtil(this.context).getConnectionSource();
	}

	public T create(T entity) {
		T enti = null;
		try {
			enti = dao.createIfNotExists(entity);
		} catch (SQLException e) {
			e.printStackTrace();
			try {
				dao.create(entity);
			} catch (SQLException e1) {
				e1.printStackTrace();
			}
		}
		return enti;
	}

	public void update(T entity) {
		try {
			dao.update(entity);
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public void delete(T entity) {
		try {
			dao.delete(entity);
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public T find(Long id) {
		T t = null;
		try {
			t = dao.queryForId(id);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return t;
	}

	public List<T> findAll() {
		List<T> list = new ArrayList<T>();
		try {
			list = getDao().queryForAll();
			
		} catch (SQLException e) {
			e.printStackTrace();
		}
		if(list == null){
			return new ArrayList<T>();
		}
		return list;
	}
	
	public ForeignCollection<Object> getEmpty(String name){
		try {
			return dao.getEmptyForeignCollection(name);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}
}
